package com.ailight.smart.gateway.filters;

import cn.hutool.core.collection.CollUtil;
import com.ailight.smart.gateway.config.AuthProperties;
import com.ailight.smart.gateway.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author: 朱海鹏
 * @Package: com.ailight.smart.gateway.filters
 * @Project: ai-light
 * @date: 2025/3/23 14:40
 * @description :
 */
@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    private final AuthProperties authProperties;

    private final JwtUtil jwtUtil;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 获取request
        ServerHttpRequest request = exchange.getRequest();
        // 2 判断是否做登录拦截
        if (isExcluded(request.getPath().toString())) {
            // 放行
            return chain.filter(exchange);
        }
        // 3 获取token
        String token;
        List<String> headers = request.getHeaders().get("authorization");
        token = CollUtil.getFirst(headers);
        // 4 校验并解析token
        Long userId;
        try {
             userId = jwtUtil.parseToken(token);
        } catch (Exception e) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 5 传递用户信息
        String userInfo = userId.toString();
        ServerWebExchange swe = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo))
                .build();
        // 6.放行
        return chain.filter(swe);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private boolean isExcluded(String path) {
        return authProperties.getExcludePaths()
                .stream()
                .anyMatch(it -> antPathMatcher.match(it, path));
    }
}
